﻿using FPSO.Models.Constant;
using FPSO.Models.Domain;
using FPSO.Models.ViewModel.Controls;
using FPSO.Services;
using FPSO.Services.Impl;
using FPSO.ViewModel.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shell;

namespace FPSO.HMI.Views.Dialog
{
    /// <summary>
    /// TaskInfoView.xaml 的交互逻辑
    /// </summary>
    public partial class TaskInfoView : Window
    {

        private ITankTaskService TaskService;
        private UCOilBallastViewModel oilViewModel;
        public List<TankTask> waitTaskList;
        public List<WBTTask> wTaskList;
        private bool bTaskCheck = false;
        private TankTask newTask = null;
        static TaskShipDataViewModel shipData;
        public TaskInfoView(int queueId, ITankTaskService taskService)
        {
            InitializeComponent();
            TaskService = taskService;
            taskQueueId = queueId;
            btn_ok.Content = "校核";
            txbTaskQueue.Text = TaskQueueConstant.GetTaskQueueName(queueId);

            sourceTank.TankId = "";
            oilViewModel = new UCOilBallastViewModel();
            shipData = new TaskShipDataViewModel();
            shipDataGrid.DataContext = shipData;

            if (queueId == TaskQueueConstant.UNLOAD_TASK_1_ID)
            {
                //外输
                ComboBoxItem outType = new ComboBoxItem() { Content = TaskTypeConstant.UNLOAD_NAME };
                ComboBoxItem swapType = new ComboBoxItem() { Content = TaskTypeConstant.SWAP_NAME };
                cmbTaskType.Items.Add(outType);
                cmbTaskType.Items.Add(swapType);
                cmbTaskType.SelectedIndex = 0;

                //隐藏是否创建压载舱任务
                panelWBTTank.Visibility = Visibility.Collapsed;
            }
            else
            {
                ComboBoxItem inType = new ComboBoxItem() { Content = TaskTypeConstant.LOAD_NAME };
                cmbTaskType.Items.Add(inType);
                cmbTaskType.SelectedIndex = 0;

                //显示是否创建压载舱任务
                panelWBTTank.Visibility = Visibility.Visible;
            }
            //Debug 任务列表获取失败，待排查
            List<TankTask> taskList = TaskService.GetWaitAndExecingCheckingTaskList(taskQueueId);
            //计算每个任务的开始时间
            if (null != taskList)
            {
                taskDic = new Dictionary<int, TankTask>();
                foreach (TankTask task in taskList)
                {
                    taskDic.Add(task.TaskId, task);
                }
                BindPreTask();
            }
            else
            {
                MessageBox.Show("获取队列" + taskQueueId + "中等待执行和、正在执行和待审核的任务失败，获取结果为：NULL");
                this.Close();
            }




            //暂时不启用PDB
            RealOilBallastServiceImpl oilBallastService = new RealOilBallastServiceImpl(SysConfig.PDBConnStr, oilViewModel);
            oilBallastService.ReflushData(DateTime.Now);

            waitTaskList = taskService.GetAllWaitAndExecingAndCheckingTaskList();
            wTaskList = new List<WBTTask>();
        }

        public static readonly DependencyProperty DialogTitleProperty =
            DependencyProperty.Register("DialogTitle", typeof(string), typeof(TaskInfoView), new PropertyMetadata("添加任务"));
        public string DialogTitle
        {
            get { return (string)GetValue(DialogTitleProperty); }
            set { SetValue(DialogTitleProperty, value); }
        }

        private void WindowMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                DragMove();
            }
        }

        private Dictionary<int, TankTask> taskDic;
        private int taskQueueId;
        private void BindPreTask()
        {
            cmbPreTask.Items.Clear();
            HashSet<int> preTaskSet = new HashSet<int>();
            foreach (TankTask task in taskDic.Values)
            {
                if (task.PreTaskId != 0)
                {
                    preTaskSet.Add(task.PreTaskId);
                }
            }
            foreach (TankTask task in taskDic.Values)
            {
                //if (preTaskSet.Contains(task.TaskId))
                {
                    ComboBoxItem item = new ComboBoxItem();
                    item.Content = task.PlanStartTime.ToString("HH:mm") + " " + TankConstant.GetTankName(task.TankId);
                    item.Tag = task.TaskId;
                    cmbPreTask.Items.Add(item);
                }
            }
        }

        private void ShowErrorMsg(string text)
        {
            MessageBox.Show(text, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
        }

        public void InitTaskConent(TankTask tankTask)
        {
            newTask = tankTask;
            taskQueueId = 1;
            SetTaskType(tankTask.TaskType);
            sourceTank.TankId = tankTask.TankId;
            txbCurVolume.Text = tankTask.InitVolm.ToString();
            txbTargetVolume.Text = tankTask.TargetVolm.ToString();
            txbPipeSpeed.Text = tankTask.PipeSpeed.ToString();

            if (tankTask.StartType == TaskStartTypeConstant.START_BY_QUEUE_ID)
            {
                QueueChecked(true, false);
                SetPreTask(tankTask.PreTaskId);
            }
            else
            {
                QueueChecked(false, true);
                ucStartTime.Value = tankTask.PlanStartTime;
                txbEndTime.Text = tankTask.PlanEndTime.ToString("yyyy-MM-dd HH:mm:ss");

                //ucStartTime_OnDateTimeChanged(ucStartTime.Value);
            }

            wTaskList = tankTask.WBTTaskList;
            ShowWBTTaskList();
        }

        private void SetPreTask(int taskId)
        {
            for (int i = 0; i < cmbPreTask.Items.Count; i++)
            {
                ComboBoxItem item = (ComboBoxItem)cmbPreTask.Items[i];
                if (Convert.ToInt32(item.Tag) == taskId)
                {
                    cmbPreTask.SelectedItem = item;
                    break;
                }
            }

            PreTask_Changed(null, null);
        }

        private void QueueChecked(bool bQueue, bool bCheck)
        {
            rbtnStartForQueue.IsChecked = bQueue;
            rbtnStartForTime.IsChecked = bCheck;
            StartType_Changed(null, null);
        }

        //测试任务合理性
        private bool CheckTaskRule()
        {
            SafeLoadAlgorithmService safeloadAlgorithm = SafeLoadAlgorithmService.GetInstance();
            TaskTankCalcService taskTankCalcService = new TaskTankCalcService(new DBTankTaskService());
            List<Dictionary<string, double>> tankDic_stags = taskTankCalcService.GetAllTankVolume(newTask);
            //Dictionary<string, double> tankDic = taskTankCalcService.GetAllTankVolume(newTask);

            List<ManualCalcResult> results = new List<ManualCalcResult>();
            List<ShipCalcState> states = new List<ShipCalcState>();
            foreach (Dictionary<string, double> tankDic in tankDic_stags)
            {
                ManualCalcResult result = safeloadAlgorithm.CallManualCalc(tankDic, 3);
                if (result != null)
                {
                    results.Add(result);
                    ShipCalcState shipCalc = result.ShipCalc;
                    // 添加结果
                    states.Add(result.ShipCalc);
                    double gm = shipCalc.GM;
                    double trim = shipCalc.Trim;
                    double heel = shipCalc.Heel;
                    double maxpermsf = shipCalc.MaxPersf;
                    double maxpermbm = shipCalc.MaxPerbm;

                    //DEBUG 这里暂时用简单的判断
                    // 判断先去掉，不然必返回false导致校核终止
                    //if (maxpermsf < 100 && maxpermbm < 100)
                    //{
                    //    return false;
                    //}
                }
            }
            // 赋值
            shipData.ShipCalcStates = states;
            shipDataGrid.Items.Refresh();
            return true;
        }

        //这里做分解，根据不同任务线做不同的处理
        private void Confirm_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (bTaskCheck == false)
                {
                    //如果newTask存在，且当前的方案为待确认或者待执行状态(TaskState = CHECK_ID || WATING_ID)，则为修改当前的方案，需要先修正整个任务时间轴
                    //DEBUG 编辑状态下仅允许修改流速、目标装载率和压载舱状态，这会导致时间轴的变化
                    if (newTask != null && (newTask.TaskType == TaskStateConstant.CHECK_ID || newTask.TaskType == TaskStateConstant.WATING_ID))
                    {
                        double pipeSpeed;
                        double.TryParse(txbPipeSpeed.Text, out pipeSpeed);
                        if (pipeSpeed <= 0 && wTaskList.Count <= 0)
                        {
                            throw new Exception("请输入正确的装卸速度!");
                        }
                        int targetVolume;
                        int.TryParse(txbTargetVolume.Text, out targetVolume);
                        if ((targetVolume < 0 || targetVolume > 100) && wTaskList.Count <= 0)
                        {
                            throw new Exception("请输入正确的目标容量!");
                        }
                        newTask.PipeSpeed = pipeSpeed;
                        newTask.TaskState = TaskStateConstant.CHECK_ID;
                        newTask.TaskResult = TaskResultConstant.UNEXEC_ID;
                        newTask.WBTTaskList = wTaskList;
                        double taskHours = CalcEndTime();
                        newTask.PlanEndTime = newTask.PlanStartTime.AddHours(taskHours);
                        newTask.UpdateTime = DateTime.Now;

                        List<TankTask> followTaskList = TaskService.GetWaitAndCheckingTaskListByTaskId(newTask.TaskId);
                        foreach (TankTask tankTask in followTaskList)
                        {
                            TankTask preTask = taskDic[tankTask.PreTaskId];
                            tankTask.StartType = TaskStartTypeConstant.START_BY_QUEUE_ID;
                            tankTask.PlanStartTime = preTask.PlanEndTime;
                            if (preTask.TaskId == newTask.TaskId)
                                tankTask.PlanStartTime = newTask.PlanEndTime;

                            double taskHours0 = CalcEndTime(tankTask);

                            tankTask.PlanEndTime = tankTask.PlanStartTime.AddHours(taskHours0);
                            TaskService.UpdateTask(tankTask);
                            taskDic[tankTask.TaskId] = tankTask;
                        }

                        //任务添加调用服务计算所有任务相关舱室液位变化情况
                        TaskTankCalcService taskTankCalcService = new TaskTankCalcService(TaskService);
                        List<TaskTankTimeFlagDetail> res = taskTankCalcService.GetAllTaskTankDetails(null);

                        //TaskService.UpdateTask(newTask);
                    }
                    else
                    {
                        if (taskQueueId == 2)
                            Confirm_inQueue2();
                        else if (taskQueueId == 3)
                            Confirm_inQueue3();
                        else
                            Confirm_inQueue1();
                    }
                    if (CheckTaskRule())
                    {
                        btn_ok.Content = "确定";
                        bTaskCheck = true;
                    }
                    return;
                }
                //校核完成并确认后再加入数据库
                TaskService.UpdateTask(newTask);
                bTaskCheck = false;
                this.Close();
            }
            catch (Exception ex)
            {
                ShowErrorMsg(ex.Message);
            }
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void AddWBTTask_Click(object sender, RoutedEventArgs e)
        {
            WBTTaskDialog wbtDialog = new WBTTaskDialog();
            wbtDialog.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            wbtDialog.ShowDialog();
            if (wbtDialog.Result == MessageBoxResult.OK)
            {
                if (wTaskList.Where(t => t.WBTTankId == wbtDialog.WBTId).Count() > 0)
                {
                    MessageBox.Show("已存在指定压载舱的任务!");
                    return;
                }

                wTaskList.Add(new WBTTask()
                {
                    WBTTankId = wbtDialog.WBTId,
                    PipeSpeed = wbtDialog.WBTSpeed,
                    TargetVolume = wbtDialog.TargetVolume,
					InitVolume = wbtDialog.InitVolume,
                    IsLoad = wbtDialog.TaskType == TaskTypeConstant.LOAD_ID
                });
                ShowWBTTaskList();
            }
        }

        private void EditWBTTask_Click(object sender, RoutedEventArgs e)
        {
            if (wbtTaskList.SelectedItem != null)
            {
                WBTTaskDisplay taskDisplay = (WBTTaskDisplay)wbtTaskList.SelectedItem;
                WBTTaskDialog wbtDialog = new WBTTaskDialog();
                wbtDialog.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                wbtDialog.WBTId = taskDisplay.WBTTankId;
                wbtDialog.WBTSpeed = taskDisplay.PipeSpeed;
                wbtDialog.TargetVolume = taskDisplay.TargetVolume;
				wbtDialog.InitVolume = taskDisplay.InitVolume;
                wbtDialog.TaskType = taskDisplay.IsLoad ? TaskTypeConstant.LOAD_ID : TaskTypeConstant.UNLOAD_ID;
				wbtDialog.Window_reload();
                wbtDialog.ShowDialog();
                if (wbtDialog.Result == MessageBoxResult.OK)
                {
                    if (wbtDialog.WBTId != taskDisplay.WBTTankId)
                    {
                        if (wTaskList.Where(t => t.WBTTankId == wbtDialog.WBTId).Count() > 0)
                        {
                            MessageBox.Show("已存在指定压载舱的任务!");
                            return;
                        }
                    }
                    for (int i = 0; i < wTaskList.Count; i++)
                    {
                        if (wTaskList[i].WBTTankId == taskDisplay.WBTTankId)
                        {
                            wTaskList[i].WBTTankId = wbtDialog.WBTId;
                            wTaskList[i].PipeSpeed = wbtDialog.WBTSpeed;
                            wTaskList[i].TargetVolume = wbtDialog.TargetVolume;
							wTaskList[i].InitVolume = wbtDialog.InitVolume;
                            wTaskList[i].IsLoad = wbtDialog.TaskType == TaskTypeConstant.LOAD_ID;
                            break;
                        }
                    }
                    ShowWBTTaskList();
                }
            }
            else
            {
                MessageBox.Show("请选择需要编辑的压载舱任务!");
            }
        }

        private void DeleteWBTTask_Click(object sender, RoutedEventArgs e)
        {
            if (wbtTaskList.SelectedItem != null)
            {
                WBTTaskDisplay taskDisplay = (WBTTaskDisplay)wbtTaskList.SelectedItem;
                wTaskList = wTaskList.Where(t => t.WBTTankId != taskDisplay.WBTTankId).ToList();
                ShowWBTTaskList();
            }
            else
            {
                MessageBox.Show("请选择需要删除的压载舱任务!");
            }
        }

        private void StartType_Changed(object sender, RoutedEventArgs e)
        {
            if (rbtnStartForTime == null || rbtnStartForQueue == null || ucStartTime == null)
                return;
            if (rbtnStartForQueue.IsChecked == null || rbtnStartForTime.IsChecked == null)
                return;

            if (rbtnStartForTime.IsChecked.Value)
            {
                ucStartTime.IsEnabled = true;
                panelPreTask.Visibility = Visibility.Collapsed;
            }
            else
            {
                ucStartTime.IsEnabled = false;
                panelPreTask.Visibility = Visibility.Visible;

                if (cmbPreTask.SelectedItem != null)
                {
                    int preTaskId = Convert.ToInt32(((ComboBoxItem)cmbPreTask.SelectedItem).Tag);
                    TankTask preTask = taskDic[preTaskId];
                    ucStartTime.Value = preTask.PlanEndTime;
                }
                else
                {
                    ucStartTime.Value = DateTime.MinValue;
                }
            }
        }

        private void Text_Changed(object sender, TextChangedEventArgs e)
        {
            try
            {
                // CalcEndTime();
            }
            catch (Exception ex)
            {
                ShowErrorMsg(ex.Message);
            }
        }
        private void TargetVolum_Changed(object sender, TextChangedEventArgs e)
        {
            try
            {
                double targetVolum;
                double.TryParse(txbTargetVolume.Text, out targetVolum);
                if (targetVolum < 0 || targetVolum > 100)
                {
                    throw new Exception("目标容量错误");
                }
                else
                {
                    // CalcEndTime();
                }
            }
            catch (Exception ex)
            {
                ShowErrorMsg(ex.Message);
            }
        }

        private void SetTaskType(int taskType)
        {
            string targetTypeName = "";
            if (taskType == TaskTypeConstant.LOAD_ID)
            {
                targetTypeName = TaskTypeConstant.LOAD_NAME;
            }
            else if (taskType == TaskTypeConstant.UNLOAD_ID)
            {
                targetTypeName = TaskTypeConstant.UNLOAD_NAME;
            }
            else if (taskType == TaskTypeConstant.SWAP_ID)
            {
                targetTypeName = TaskTypeConstant.SWAP_NAME;
            }
            //cmbTaskType.SelectedIndex = taskType;
            for (int i = 0; i < cmbTaskType.Items.Count; i++)
            {
                ComboBoxItem taskTypeItem = (ComboBoxItem)cmbTaskType.Items[i];
                if (targetTypeName.Equals(taskTypeItem.Content.ToString()))
                {
                    cmbTaskType.SelectedIndex = i;
                }
            }
        }

        private int GetTaskType()
        {
            ComboBoxItem taskType = (ComboBoxItem)cmbTaskType.SelectedItem;
            if (taskType != null)
            {
                string typeContent = taskType.Content.ToString();
                if (typeContent.Equals(TaskTypeConstant.LOAD_NAME))
                {
                    return TaskTypeConstant.LOAD_ID;
                }
                else if (typeContent.Equals(TaskTypeConstant.UNLOAD_NAME))
                {
                    return TaskTypeConstant.UNLOAD_ID;
                }
                else if (typeContent.Equals(TaskTypeConstant.SWAP_NAME))
                {
                    return TaskTypeConstant.SWAP_ID;
                }
            }

            return TaskTypeConstant.DEFAULT_ID;
        }

        private void TaskType_Changed(object sender, SelectionChangedEventArgs e)
        {
            if (GetTaskType() == TaskTypeConstant.SWAP_ID)
            {
                panelTarget1.Visibility = Visibility.Visible;
            }
            else
            {
                panelTarget1.Visibility = Visibility.Collapsed;
            }

            if (GetTaskType() == TaskTypeConstant.LOAD_ID)
            {
                rbtnStartForQueue.IsEnabled = true;
            }
            else
            {
                rbtnStartForTime.IsChecked = true;
                rbtnStartForQueue.IsEnabled = false;
            }
        }

        private void PreTask_Changed(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (cmbPreTask.SelectedItem != null)
                {
                    int preTaskId = Convert.ToInt32(((ComboBoxItem)cmbPreTask.SelectedItem).Tag);
                    TankTask preTask = taskDic[preTaskId];
                    ucStartTime.Value = preTask.PlanEndTime;
                }
                CalcEndTime();
            }
            catch (Exception ex)
            {
                ShowErrorMsg(ex.Message);
            }
        }

        //默认经过该方法重新计算的TankTask都是装载过程
        private double CalcEndTime(TankTask localTankTask)
        {
            if (double.IsNaN(localTankTask.InitVolm) || double.IsNaN(localTankTask.TargetVolm) || double.IsNaN(localTankTask.PipeSpeed))
            {
                return 0;
            }
            DateTime startTime = DateTime.MinValue;
            if (localTankTask.StartType == 1)
            {
                startTime = ucStartTime.Value;
            }
            else if (localTankTask.StartType == 2)
            {
                int preTaskId = localTankTask.PreTaskId;
                TankTask preTask = taskDic[preTaskId];
                startTime = preTask.PlanEndTime;
            }

            if (!(localTankTask.PipeSpeed <= 0 || localTankTask.TargetVolm < 0 || localTankTask.TargetVolm > 100 || startTime == DateTime.MinValue || localTankTask.TankId == ""))
            {
                do
                {
                    //DEBUG 后面这部分这样处理的目的是什么？
                    double currentVolum = GetSourceTankTargetVolume(localTankTask.TankId, localTankTask.InitVolm);
                    double totalVolum = TankConstant.GetTankVolume(localTankTask.TankId);
                    double taskVolum = (localTankTask.TargetVolm * 0.01 * totalVolum) - currentVolum;
                    double taskHours = 0;
                    if (Math.Abs(taskVolum) > 1)
                    {
                        int taskType = GetTaskType();
                        if (taskType == TaskTypeConstant.LOAD_ID)
                        {
                            if (taskVolum < -1.0)
                            {
                                throw new Exception("目标容量小于或等于当前容量,数据不合法!");
                            }
                        }
                        else
                        {
                            if (taskVolum > 1.0)
                            {
                                throw new Exception("目标容量大于或等于当前容量,数据不合法!");
                            }
                        }
                        taskHours = Math.Abs(taskVolum) / localTankTask.PipeSpeed;
                    }

                    if (taskHours > 36 && localTankTask.WBTTaskList.Count <= 0)
                    {
                        throw new Exception("任务时间过长，执行时间超过36小时");
                    }
                    if (taskHours < 2 && localTankTask.WBTTaskList.Count <= 0)
                    {
                        throw new Exception("任务时间太短，执行时间少于2小时");
                    }

                    return taskHours;
                }
                while (false);
            }
            return 0;
        }
        private double CalcEndTime()
        {
            DateTime startTime = DateTime.MinValue;

            if (string.IsNullOrEmpty(txbPipeSpeed.Text) || string.IsNullOrEmpty(txbTargetVolume.Text))
            {
                txbEndTime.Text = "";
                return 0;
            }

            double pipeSpeed;
            double.TryParse(txbPipeSpeed.Text, out pipeSpeed);
            double targetVolum;
            double.TryParse(txbTargetVolume.Text, out targetVolum);

            if ((bool)rbtnStartForTime.IsChecked)
            {
                startTime = ucStartTime.Value;
            }
            else if (cmbPreTask.SelectedItem != null)
            {
                int preTaskId = Convert.ToInt32(((ComboBoxItem)cmbPreTask.SelectedItem).Tag);
                TankTask preTask = taskDic[preTaskId];
                startTime = preTask.PlanEndTime;
            }

            if (!(pipeSpeed <= 0 || targetVolum < 0 || targetVolum > 100 || startTime == DateTime.MinValue || sourceTank.TankId == ""))
            {
                do
                {
                    //DEBUG 后面这部分这样处理的目的是什么？
                    double currentVolum = GetSourceTankCurrentVolume(sourceTank.TankId);
                    if (newTask != null)
                        currentVolum = GetSourceTankTargetVolume(sourceTank.TankId, newTask.InitVolm);
                    double totalVolum = TankConstant.GetTankVolume(sourceTank.TankId);
                    double taskVolum = (targetVolum * 0.01 * totalVolum) - currentVolum;
                    double taskHours = 0;
                    if (Math.Abs(taskVolum) > 1)
                    {
                        int taskType = GetTaskType();
                        if (taskType == TaskTypeConstant.LOAD_ID)
                        {
                            if (taskVolum < -1.0)
                            {
                                throw new Exception("目标容量小于或等于当前容量,数据不合法!");
                            }
                        }
                        else
                        {
                            if (taskVolum > 1.0)
                            {
                                throw new Exception("目标容量大于或等于当前容量,数据不合法!");
                            }
                        }
                        taskHours = Math.Abs(taskVolum) / pipeSpeed;
                    }

                    if (taskHours > 36 && wTaskList.Count <= 0)
                    {
                        throw new Exception("任务时间过长，执行时间超过36小时");
                    }
                    if (taskHours < 2 && wTaskList.Count <= 0)
                    {
                        throw new Exception("任务时间太短，执行时间少于2小时");
                    }

                    txbEndTime.Text = startTime.AddHours(taskHours).ToString("yyyy-MM-dd HH:mm:ss");

                    return taskHours;
                }
                while (false);
            }

            txbEndTime.Text = "";
            return 0;
        }

        private void sourceTank_OnTankChanged(string tankId)
        {
            try
            {
                CalcEndTime();
                if (sourceTank.TankId == "")
                {
                    txbCurVolume.Text = "0";
                }
                else
                {
                    if (newTask == null)
                    {
                        double currentVolum = GetSourceTankCurrentVolume(sourceTank.TankId);
                        double totalVolum = TankConstant.GetTankVolume(sourceTank.TankId);
                        txbCurVolume.Text = Convert.ToInt32(currentVolum * 100 / totalVolum).ToString();
                    }
                    else
                    {
                        double initVolum = newTask.InitVolm;
                        txbCurVolume.Text = Convert.ToString(initVolum);
                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrorMsg(ex.Message);
            }
        }

        private double GetSourceTankCurrentVolume(string tankId)
        {
            //获取当前选择舱室的容量
            TankOilViewModel tankOilViewModel = oilViewModel.GetCotViewModel(tankId);
            double totalVolum = tankOilViewModel.TotalVolume;
            double currentVolum = tankOilViewModel.Volume;
            TankTask lastSourceTask = waitTaskList.Where(t => t.SwapTargetTank1 == sourceTank.TankId).LastOrDefault();
            TankTask lastTargetTask = waitTaskList.Where(t => t.TankId == sourceTank.TankId).LastOrDefault();
            if (lastSourceTask != null)
            {
                currentVolum = lastSourceTask.TargetVolm * 0.01 * totalVolum;
            }

            if (lastTargetTask != null)
            {
                if (lastSourceTask == null || lastTargetTask.PlanStartTime > lastSourceTask.PlanStartTime)
                {
                    currentVolum += lastTargetTask.PipeSpeed * (lastTargetTask.PlanEndTime - lastTargetTask.PlanStartTime).TotalHours;
                }
            }
            return currentVolum;
        }
        private double GetSourceTankTargetVolume(string tankId, double volume)
        {
            //获取当前选择舱室的容量
            TankOilViewModel tankOilViewModel = oilViewModel.GetCotViewModel(tankId);
            double totalVolum = tankOilViewModel.TotalVolume;
            double currentVolum = volume * 0.01 * totalVolum;
            return currentVolum;
        }

        private void ucStartTime_OnDateTimeChanged(DateTime obj)
        {
            try
            {
                CalcEndTime();
            }
            catch (Exception ex)
            {
                ShowErrorMsg(ex.Message);
            }
        }

        private void ShowWBTTaskList()
        {
            List<WBTTaskDisplay> displayList = new List<WBTTaskDisplay>();
            foreach (WBTTask wbt in wTaskList)
            {
                WBTTaskDisplay taskDisplay = new WBTTaskDisplay();
                taskDisplay.WBTTankId = wbt.WBTTankId;
                taskDisplay.WBTTankName = TankConstant.GetTankName(wbt.WBTTankId);
                taskDisplay.PipeSpeed = wbt.PipeSpeed;
                taskDisplay.IsLoad = wbt.IsLoad;
                taskDisplay.TargetVolume = wbt.TargetVolume;
				taskDisplay.InitVolume = wbt.InitVolume;
                taskDisplay.LoadType = wbt.IsLoad ? TaskTypeConstant.LOAD_NAME : TaskTypeConstant.UNLOAD_NAME;
                displayList.Add(taskDisplay);
            }
            wbtTaskList.ItemsSource = displayList;
        }

        private void UpdateTankTask(TankTask oriTankTask, TankTask importTankTask)
        {

        }

        //任务线1的操作，装载过程
        private void Confirm_inQueue1()
        {
            double pipeSpeed;
            double.TryParse(txbPipeSpeed.Text, out pipeSpeed);
            if (pipeSpeed <= 0 && wTaskList.Count <= 0)
            {
                throw new Exception("请输入正确的装卸速度!");
            }

            int initVolume;
            int.TryParse(txbCurVolume.Text, out initVolume);

            int targetVolume;
            int.TryParse(txbTargetVolume.Text, out targetVolume);
            if ((targetVolume < initVolume || targetVolume > 100) && wTaskList.Count <= 0)
            {
                throw new Exception("请输入正确的目标容量!");
            }

            if (sourceTank.TankId == "" && wTaskList.Count <= 0)
            {
                throw new Exception("请设置操作舱室!");
            }

            TankTask task = new TankTask();
            task.TaskQueueId = taskQueueId;
            task.TaskName = string.Empty;
            task.TaskType = GetTaskType();
            task.TankId = sourceTank.TankId;
            task.InitVolm = initVolume;
            task.TargetVolm = targetVolume;
            task.PipeSpeed = pipeSpeed;
            task.TaskState = TaskStateConstant.CHECK_ID;
            task.TaskResult = TaskResultConstant.UNEXEC_ID;

            task.WBTTaskList = wTaskList;

            if ((bool)rbtnStartForTime.IsChecked)
            {
                task.StartType = TaskStartTypeConstant.START_BY_TIME_ID;
                task.PreTaskId = 0;
                task.PlanStartTime = ucStartTime.Value;

            }
            else
            {
                if (cmbPreTask.SelectedItem == null)
                {
                    throw new Exception("请选择前置任务");
                }

                task.PreTaskId = Convert.ToInt32(((ComboBoxItem)cmbPreTask.SelectedItem).Tag);
                TankTask preTask = taskDic[task.PreTaskId];
                task.StartType = TaskStartTypeConstant.START_BY_QUEUE_ID;
                task.PlanStartTime = preTask.PlanEndTime;
            }

            for (int i = waitTaskList.Count - 1; i >= 0; i--)
            {
                TankTask tmpTask = waitTaskList[i];
                if (tmpTask.TaskQueueId == task.TaskQueueId)
                {
                    if (task.PlanStartTime < tmpTask.PlanEndTime)
                    {
                        throw new Exception($"当前任务只能设置在({tmpTask.PlanEndTime.ToString("yyyy-MM-dd HH:mm:ss")})后");
                    }
                    break;
                }
            }

            double taskHours = CalcEndTime();

            task.PlanEndTime = task.PlanStartTime.AddHours(taskHours);

            task.ExecStartTime = DateTime.MinValue;
            task.ExecEndTime = DateTime.MinValue;
            task.CreateTime = DateTime.Now;
            task.UpdateTime = DateTime.Now;
            task.DeleteTime = DateTime.MinValue;

            newTask = task;
        }
        private void Confirm_inQueue2()
        {
            double pipeSpeed;
            double.TryParse(txbPipeSpeed.Text, out pipeSpeed);
            if (pipeSpeed <= 0 && wTaskList.Count <= 0)
            {
                throw new Exception("请输入正确的装卸速度!");
            }

            int initVolume;
            int.TryParse(txbCurVolume.Text, out initVolume);
            int targetVolume;
            int.TryParse(txbTargetVolume.Text, out targetVolume);
            if ((targetVolume < initVolume || targetVolume > 100) && wTaskList.Count <= 0)
            {
                throw new Exception("请输入正确的目标容量!");
            }

            if (sourceTank.TankId == "" && wTaskList.Count <= 0)
            {
                throw new Exception("请设置操作舱室!");
            }

            TankTask task = new TankTask();
            task.TaskQueueId = taskQueueId;
            task.TaskName = string.Empty;
            task.TaskType = GetTaskType();
            task.TankId = sourceTank.TankId;
            task.InitVolm = initVolume;
            task.TargetVolm = targetVolume;
            task.PipeSpeed = pipeSpeed;
            task.TaskState = TaskStateConstant.CHECK_ID;
            task.TaskResult = TaskResultConstant.UNEXEC_ID;


            task.WBTTaskList = wTaskList;

            if ((bool)rbtnStartForTime.IsChecked)
            {
                task.StartType = TaskStartTypeConstant.START_BY_TIME_ID;
                task.PreTaskId = 0;
                task.PlanStartTime = ucStartTime.Value;

            }
            else
            {
                if (cmbPreTask.SelectedItem == null)
                {
                    throw new Exception("请选择前置任务");
                }

                task.PreTaskId = Convert.ToInt32(((ComboBoxItem)cmbPreTask.SelectedItem).Tag);
                TankTask preTask = taskDic[task.PreTaskId];
                task.StartType = TaskStartTypeConstant.START_BY_QUEUE_ID;
                task.PlanStartTime = preTask.PlanEndTime;
            }

            //任务线2加舱室，会多一步检查，该舱室装载过程中，任务线1中不能有相同舱室同时参与动作
            for (int i = waitTaskList.Count - 1; i >= 0; i--)
            {
                TankTask waitTask = waitTaskList[i];
                DateTime newTaskStartTime = task.PlanStartTime;
                DateTime newTaskEndTime = task.PlanEndTime;
                DateTime waitTaskStartTime = waitTask.PlanStartTime;
                DateTime waitTaskEndTime = waitTask.PlanEndTime;

                if (waitTask.TaskQueueId == task.TaskQueueId)
                {
                    if (newTaskStartTime < waitTaskEndTime)
                    {
                        throw new Exception($"当前任务只能设置在({waitTask.PlanEndTime.ToString("yyyy-MM-dd HH:mm:ss")})后");
                    }
                    break;
                }
                else
                {
                    //这里只检查同舱室的过程
                    if (waitTask.TankId == task.TankId)
                    {
                        if ((newTaskStartTime > waitTaskStartTime && newTaskStartTime < waitTaskEndTime)
                            || (newTaskEndTime > waitTaskStartTime && newTaskEndTime < waitTaskEndTime))
                        {
                            throw new Exception($"当前任务只能设置在({waitTaskStartTime.ToString("yyyy-MM-dd HH:mm:ss")},{waitTaskEndTime.ToString("yyyy-MM-dd HH:mm:ss")})范围外");
                        }
                        break;
                    }
                }
            }

            double taskHours = CalcEndTime();

            task.PlanEndTime = task.PlanStartTime.AddHours(taskHours);

            task.ExecStartTime = DateTime.MinValue;
            task.ExecEndTime = DateTime.MinValue;
            task.CreateTime = DateTime.Now;
            task.UpdateTime = DateTime.Now;
            task.DeleteTime = DateTime.MinValue;

            newTask = task;
        }
        private void Confirm_inQueue3()
        {
            try
            {
                if (bTaskCheck == false)
                {
                    //如果newTask存在，且当前的方案为待确认或者待执行状态(TaskState = CHECK_ID || WATING_ID)，则为修改当前的方案，需要先修正整个任务时间轴
                    //DEBUG 编辑状态下仅允许修改流速、目标装载率和压载舱状态，这会导致时间轴的变化
                    if (newTask != null && (newTask.TaskType == TaskStateConstant.CHECK_ID || newTask.TaskType == TaskStateConstant.WATING_ID))
                    {
                        double pipeSpeed;
                        double.TryParse(txbPipeSpeed.Text, out pipeSpeed);
                        if (pipeSpeed <= 0 && wTaskList.Count <= 0)
                        {
                            throw new Exception("请输入正确的装卸速度!");
                        }
                        int targetVolume;
                        int.TryParse(txbTargetVolume.Text, out targetVolume);
                        if ((targetVolume < 0 || targetVolume > 100) && wTaskList.Count <= 0)
                        {
                            throw new Exception("请输入正确的目标容量!");
                        }
                        newTask.PipeSpeed = pipeSpeed;
                        newTask.TaskState = TaskStateConstant.CHECK_ID;
                        newTask.TaskResult = TaskResultConstant.UNEXEC_ID;
                        newTask.WBTTaskList = wTaskList;
                        double taskHours = CalcEndTime();
                        newTask.PlanEndTime = newTask.PlanStartTime.AddHours(taskHours);
                        newTask.UpdateTime = DateTime.Now;

                        List<TankTask> followTaskList = TaskService.GetWaitAndCheckingTaskListByTaskId(newTask.TaskId);
                        foreach (TankTask tankTask in followTaskList)
                        {
                            TankTask preTask = taskDic[tankTask.PreTaskId];
                            tankTask.StartType = TaskStartTypeConstant.START_BY_QUEUE_ID;
                            tankTask.PlanStartTime = preTask.PlanEndTime;
                            if (preTask.TaskId == newTask.TaskId)
                                tankTask.PlanStartTime = newTask.PlanEndTime;

                            double taskHours0 = CalcEndTime(tankTask);

                            tankTask.PlanEndTime = tankTask.PlanStartTime.AddHours(taskHours0);
                            TaskService.UpdateTask(tankTask);
                            taskDic[tankTask.TaskId] = tankTask;
                        }

                        //任务添加调用服务计算所有任务相关舱室液位变化情况
                        TaskTankCalcService taskTankCalcService = new TaskTankCalcService(TaskService);
                        List<TaskTankTimeFlagDetail> res = taskTankCalcService.GetAllTaskTankDetails(null);

                        //TaskService.UpdateTask(newTask);
                    }
                    else
                    {
                        double pipeSpeed;
                        double.TryParse(txbPipeSpeed.Text, out pipeSpeed);
                        if (pipeSpeed <= 0 && wTaskList.Count <= 0)
                        {
                            throw new Exception("请输入正确的装卸速度!");
                        }

                        int targetVolume;
                        int.TryParse(txbTargetVolume.Text, out targetVolume);
                        if ((targetVolume < 0 || targetVolume > 100) && wTaskList.Count <= 0)
                        {
                            throw new Exception("请输入正确的目标容量!");
                        }

                        if (sourceTank.TankId == "" && wTaskList.Count <= 0)
                        {
                            throw new Exception("请设置操作舱室!");
                        }

                        int initVolume;
                        int.TryParse(txbCurVolume.Text, out initVolume);

                        TankTask task = new TankTask();
                        task.TaskQueueId = taskQueueId;
                        task.TaskName = string.Empty;
                        task.TaskType = GetTaskType();
                        task.TankId = sourceTank.TankId;
                        task.InitVolm = initVolume;
                        task.TargetVolm = targetVolume;
                        task.PipeSpeed = pipeSpeed;
                        task.TaskState = TaskStateConstant.CHECK_ID;
                        task.TaskResult = TaskResultConstant.UNEXEC_ID;

                        //DEBUG 外输和倒舱需要另外开启一个对话框设置，避免逻辑冲突
                        task.SwapTargetTank1 = "";
                        if (task.TaskType == TaskTypeConstant.SWAP_ID)
                        {
                            //倒仓，需要设置目标舱
                            if (targetTank1.TankId == "")
                            {
                                throw new Exception("请设置倒仓任务的目标舱");
                            }
                            task.SwapTargetTank1 = targetTank1.TankId;
                        }

                        task.WBTTaskList = wTaskList;

                        if ((bool)rbtnStartForTime.IsChecked)
                        {
                            /*
							if (ucStartTime.Value < DateTime.Now.AddMinutes(10) && wTaskList.Count <= 0)
							{
								throw new Exception("开始时间错误，不能设定距离现在十分钟内的任务");
							}
							*/
                            task.StartType = TaskStartTypeConstant.START_BY_TIME_ID;
                            task.PreTaskId = 0;
                            task.PlanStartTime = ucStartTime.Value;

                        }
                        else
                        {
                            if (cmbPreTask.SelectedItem == null)
                            {
                                throw new Exception("请选择前置任务");
                            }

                            task.PreTaskId = Convert.ToInt32(((ComboBoxItem)cmbPreTask.SelectedItem).Tag);
                            TankTask preTask = taskDic[task.PreTaskId];
                            task.StartType = TaskStartTypeConstant.START_BY_QUEUE_ID;
                            task.PlanStartTime = preTask.PlanEndTime;
                        }

                        for (int i = waitTaskList.Count - 1; i >= 0; i--)
                        {
                            TankTask tmpTask = waitTaskList[i];
                            if (tmpTask.TaskQueueId == task.TaskQueueId)
                            //if (tmpTask.TankId == task.TankId || tmpTask.SwapTargetTank1 == task.TankId || tmpTask.TankId == task.SwapTargetTank1
                            //	|| (tmpTask.SwapTargetTank1 != "" && tmpTask.SwapTargetTank1 == task.SwapTargetTank1))
                            {
                                if (task.PlanStartTime < tmpTask.PlanEndTime)
                                {
                                    throw new Exception($"当前任务只能设置在({tmpTask.PlanEndTime.ToString("yyyy-MM-dd HH:mm:ss")})后");
                                }
                                break;
                            }
                        }

                        double taskHours = CalcEndTime();

                        task.PlanEndTime = task.PlanStartTime.AddHours(taskHours);

                        task.ExecStartTime = DateTime.MinValue;
                        task.ExecEndTime = DateTime.MinValue;
                        task.CreateTime = DateTime.Now;
                        task.UpdateTime = DateTime.Now;
                        task.DeleteTime = DateTime.MinValue;

                        newTask = task;
                    }
                    //DEBUG 在现有的TaskList中不能包含同液货舱的不同动作，可能需要修改
                    if (CheckTaskRule())
                    {
                        btn_ok.Content = "确定";
                        bTaskCheck = true;
                    }
                    return;
                }

                //校核完成并确认后再加入数据库
                TaskService.UpdateTask(newTask);
                bTaskCheck = false;
                this.Close();
            }
            catch (Exception ex)
            {
                ShowErrorMsg(ex.Message);
            }
        }
    }
}
